<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Models\Box;
use App\Models\BoxAddress;
use App\Models\Colour;
use App\Models\BoxDeliver;
use App\Models\Comment;
use App\Models\BoxCollocation;
use App\Models\BoxCare;
use App\Models\UsersWechat;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Validator;
class BoxController extends Controller
{
    public function __construct()
    {
        $this->middleware('admin');
    }

    public function index(Request $request){
        $type = intval($request->input('type',0));
    	$status = intval($request->input('status',1));
    	$page = intval($request->input('page',1));
    	$username = safe2($request->input('username'));
    	$mobile = safe2($request->input('mobile'));
    	$datetime = $request->input('datetime');
        $userNumber = $request->input('userNumber');
        $no = $request->input('no');

        $query = Box::select('*');

        if ($status!=-1) {
            if ($status==1) {
                $query->where('status',1)->whereDate('delivery_at','<',date('Ymd', strtotime("+15 day")))->count();//date('Ymd', strtotime("+15 day"))
            }else{
                $query->where('status',$status);
            }
        }

        if ($status==6) {
            $query->orderBy('updated_at','DESC');
        }else{
            $query->orderBy('delivery_at','ASC');
        }


        if ($type==1) {
            $query->where('type',1)->where('to_wechat_id','>',0);
        }
        if ($userNumber) {
            $user= UsersWechat::where('number',$userNumber)->first();
            $query ->where('wechat_id',$user->id);
        }

        if ($username || $mobile) {
            $Address = BoxAddress::select('box_id')->where('type','box');
            if ($username) {
                $Address->where('username','like','%'.$username.'%');
            }
            if ($mobile) {
                if (!isMobile($mobile)) {
                    return $this->error('手机格式不正确');
                }
                $Address->where('phone',$mobile);
            }
            
            $rows = $Address->get();
            $ids = [];
            foreach ($rows as $key => $row) {
                array_push($ids, $row->box_id);
            }
            $query->whereIn('id',$ids);
        }


        if ($datetime || $no) {
            $query2  = BoxDeliver::select('id');
            if ($datetime) {
                $query2->whereDate('delivery_at',$datetime);
            }
            if ($no) {
                $query2->orWhere('no',$no);
            }
            $query2 = $query2->get();
            $ids = [];
            foreach ($query2 as $key => $row) {
                array_push($ids, $row->id);
            }
            $query->whereIn('id',$ids);
        }

        $rows   =  $query->paginate(15);
        foreach ($rows as $key => $row) {
            $row->collocation = BoxCollocation ::where('box_id',$row->id)->get();
            $row->address = BoxAddress::where('box_id',$row->id)->where('type','box')->first();
            $row->delive = BoxDeliver::where(['box_id'=>$row->id,'type'=>'box'])->first();
            $row->statusName = $row->getStatusName();
            $row->userName = $row->getUserName($row->wechat_id);
            if ($row->type==1) {
                $row->toUserName = $row->getUserName($row->to_wechat_id);
            }
        }
        $data = [
            'rows'=>$rows,
            'status'=>$status,
            'type'=>$type,
        ];
        if($request->ajax()){
        	return $this->response($data);
        }

        $data['colours'] = Colour::get();
        return view('admin/box/box_list', $data);
    }

    public function getBoxInfo($box_id){
        //取profile 因为和用户信息使用同一个模版 需要和user 资料保持一致
        $profile = Box::find($box_id);
        if (!$profile) {
            return $this->error('盒子不存在');
        }
        $profile->sex = $profile->sex ==1 ? '男':'女';
        $user = UsersWechat::find($profile->wechat_id);
        if (!$user) {
            return $this->error('用户不存在');
        }
        if ($user->type==0) {
            return $this->error('该用户暂不是会员');
        }

        $box1 = Box::where('wechat_id',$profile->wechat_id)->where('type',0)->count('id');
        $box2 = Box::where('wechat_id',$profile->wechat_id)->where('type',1)->count('id');
        $box3 = Box::where('to_wechat_id',$profile->wechat_id)->count('id');
        $boxCare1 = BoxCare::where('wechat_id',$profile->wechat_id)->count('id');
        $boxCare2 = BoxCare::where('wechat_id',$profile->wechat_id)->where('is_frozen',1)->count('id');
        $boxCare3 = BoxCare::where('wechat_id',$profile->wechat_id)->where('is_frozen',0)->count('id');
        $boxArr = [
            'box1'=>$box1,
            'box2'=>$box2,
            'box3'=>$box3,
            'boxCare1'=>$boxCare1,
            'boxCare2'=>$boxCare2,
            'boxCare3'=>$boxCare3,
        ];

        $data = compact('user','profile','boxArr');

        return $this->response($data);
    }

    public function getCollocationPageRows(Request $request,$box_id){
        $box = Box::find($box_id);
        $type = $request->input('type');
        if (!$box) {
            return $this->error('盒子不存在');
        }
        if ($type=='history') {
             $rows = BoxCollocation::where('wechat_id',$box->wechat_id)->paginate(15);
        }else{
            $rows = BoxCollocation::where('box_id',$box_id)->get();
        }

        foreach ($rows as $key => $row) {
            $box = Box::find($row->box_id);
            $row->boxNumer = $box->number;
        }
        $data =['box'=>$box,'rows'=>$rows];
        return $this->response($data);
    }


    public function postChange(Request $request){
        $id = intval($request->input('id'));
        $param = $request->input('param');
        if (!is_array($param)) {
            return $this->error('参数错误');
        }
        $box = Box::find($id);
        if (!$box) {
            return $this->error('关怀盒子不存在');
        }
        foreach ($param as $key => $value) {
            $box->$key = $value;
            $box->Save();
        }
        $box->save();
        return $this->response('ok');
    }

    public function postCollocationInfo(Request $request){
        $id = intval($request->input('id'));
        $row = BoxCollocation::where('id',$id)->first();
        if (!$row) {
            return $this->error('搭配不存在');
        }

        $rows = BoxCollocation::where('box_id',$row->box_id)->get();
        foreach ($rows as $key => $row) {
            $box = Box::find($row->box_id);
            $row->boxNumer = $box->number;
            $row->pic = unserialize($row->pic);
            $colour = Colour::select('name')->find($row->colour_id);
            $row->colour = $colour->name;
        }
        if ($row) {
            return $this->response(['rows'=>$rows,'row'=>$row]);
        }else{
            return $this->error('搭配不存在');
        }
    }

    public function postSend(Request $request){
        $id = intval($request->input('id'));
        $box = Box::find($id);
        if (!$box) {
            return $this->error('盒子不存在');
        }
        if ($box->status!=3) {
            return $this->error('该盒子还未搭配；不可发货');
        }
        $row = BoxDeliver::where('box_id',$id)->first();
        if ($row) {
            return $this->error('盒子已存在发货信息');
        }
        $name = safe2($request->input('name'));
        $no = safe2($request->input('no'));
        $estimate_at = $request->input('estimate_at');
        $row = new BoxDeliver;
        $row->box_id = $box->id;
        $row->name = $name;
        $row->no = $no;
        $row->estimate_at = $estimate_at;
        $row->delivery_at = date('Y-m-d H:i:s');
        $row->type='box';
        $row->Save();
        $box->status=4;
        $box->Save();

        return $this->response('ok');
    }

    public function postCollocation(Request $request){
        $validator = Validator::make($request->all(),
            [
                'box_id' => 'required|integer',
                'title' => 'required',
                'style_number' => 'required',
                'price' => 'required',
                'p_number' => 'required',
                'size' => 'required',
                'colour' => 'required',
                'pic' => 'required',
            ],[
                'required' => '字段 :attribute 不能为空.',
                'integer'=>'字段 :attribute 必须是数值',
            ]);
        if ($validator->fails()) {
            $messages = $validator->errors();
            return response()->json(['code' => -1,'msg' => $messages->first(),'data' => '',]);
        }

        $box_id = intval($request->input('box_id'));
        $title = safe2($request->input('title'));
        $style_number = safe2($request->input('style_number'));
        $price = intval($request->input('price'));
        $p_number = intval($request->input('p_number',1));
        $pic = safe2($request->input('pic'));
        $size = safe2($request->input('size'));
        $colour = safe2($request->input('colour'));
        $id = intval($request->input('id'));

        $box = Box::find($box_id);
        if (empty($box)) {
            return $this->error('盒子不存在');
        }
        if ($id) {
            $row = BoxCollocation::find($id);
        }else{
            $row = new BoxCollocation;
            $row->box_id = $box->id;
            $row->wechat_id= $box->wechat_id;
        }
        $row->pic = $pic;
        $row->colour =  $colour;
        $row->style_number=$style_number;
        $row->size=$size;
        $row->title=$title;
        $row->price=$price;
        $row->p_number=$p_number;
        $row->save();
        $n = BoxCollocation::select('id')->where('box_id',$box_id)->count('id');

        if ($n>0) {
            $box->status=3;//已搭配待邮寄
            $box->Save();
        }
        return $this->response('ok');
    }

    public function postdeleteCollocation(Request $request){
        $validator = Validator::make($request->all(),
            [
                'box_id' => 'required|integer',
                'id' => 'required|integer',
            ],[
                'required' => '字段 :attribute 不能为空.',
                'integer'=>'字段 :attribute 必须是数值',
            ]);
        if ($validator->fails()) {
            $messages = $validator->errors();
            return response()->json(['code' => -1,'msg' => $messages->first(),'data' => '',]);
        }
        $box_id = intval($request->input('box_id'));
        $id = intval($request->input('id'));

        $box = Box::find($box_id);
        if (empty($box)) {
            return $this->error('盒子不存在');
        }
        BoxCollocation::where('id',$id)->where('box_id',$box_id)->delete();
        return $this->response('ok');
    }



    public function comment($id)
    {
        $Box = Box::find($id);
        if (!$Box) {
            return $this->error('该盒子不存在');
        }
        if ($Box->status!=6) {
            return $this->error('该盒子还未完成');
        }
        $row= Comment::where('box_id',$id)->first();
        if ($row) {
            $clothing_score = $row->clothing_score;
            foreach ($clothing_score as $key => $value) {
                $clothing_score[$key]['collocation'] = BoxCollocation::find($key);
            }
            $row->clothing = $clothing_score;
            return $this->response(compact('row','Box'));
        }else{
            return $this->error('暂无评论');
        }

    }

    //查看收货信息
    public function getSendAddress(Request $request){
        $id = intval($request->input('id'));
        $row = BoxAddress::where('type','box')->where('box_id',$id)->first();
        if (empty($row)) {
            return $this->error('该关怀盒子还未填写邮寄信息！');
        }
        return $this->response(compact('row'));
    }

    public function getBoxGive(Request $request)
    {
        return view('admin/box/box_give');
    }

}
